package com.dataart.productshop.file.utils;

import com.dataart.productshop.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Component
public class SavePicture {

    public boolean savePictures(CommonsMultipartFile pictureCMF, String folderPath) {
        boolean errInSaving = false;
        if (pictureCMF != null && !pictureCMF.isEmpty()) {
            String currentFileName = pictureCMF.getOriginalFilename();
            File pictureFile = new File(folderPath + "/" + currentFileName);
            if(!createFile(pictureFile)){
                return false;
            }
            try {
                BufferedImage currImage = ResizeImage.resizeStreamImage(pictureCMF.getInputStream());
                if (currImage != null) {
                    //it already was checked

                    String extention = StringUtils.getFirstExpr(currentFileName, Constants.EXT_EXPR);
                    ImageIO.write(currImage, extention, pictureFile);
                } else {
                    //resizing on a place
                    pictureCMF.transferTo(pictureFile);
                    ResizeImage.resizeImage(folderPath + "/" + currentFileName);
                }

            } catch (IOException ioe) {
                System.err.println("error in reading file" + currentFileName);
                //TODO: remove all System.out and System.err from the project. Replace them with Log4j or, even better slf4j http://goo.gl/6ryAR
                return false;
            } catch (IllegalStateException ise) {
                System.err.println("error in transfer file" + currentFileName);
                return false;
            }
        }
        return true;
    }

    public boolean createFile(File file){
        if(!file.exists()){
            if(!file.getParentFile().exists()){
                file.mkdirs();
            }
            try {
                file.createNewFile();
            } catch (IOException e) {
                //TODO add property message
                System.err.println("cant create file");
                return false;
            }
        }
        return file.exists();
    }
}
